#include "getfile.h"
extern int WriteOrRead;//0读，1写

void GetFile(int peerfd,char* filename)
{
    printf("in GetFile peerfd = %d,filename = %s\n",peerfd,filename);
    //1.先接收文件长度
    size_t filelength = 0;
    recvCircle(peerfd,(char*)&filelength,8);

    //2.打开文件。返回文件大小，实现断点续传
    int fd = open(filename,O_CREAT | O_RDWR,0664);
    struct stat st;
    memset(&st,0,sizeof(st));
    fstat(fd,&st);
    send(peerfd,&st.st_size,8,MSG_WAITALL);
    //2.1移动文件读写指针到文件末尾
    lseek(fd,0,SEEK_END);

    //3.接收文件.没有判断是否断开连接
    char recvbuf[1024] = {0};
    while(filelength > st.st_size)
    {
        memset(&recvbuf,0,1024);
        int len = 0;
        recvCircle(peerfd,(char*)&len,4);
        recvCircle(peerfd,recvbuf,len);
        write(fd,recvbuf,len);
        filelength -= len;
    }
    
    close(fd);
}

